package com.weirdor.mongo;

import cn.hutool.core.convert.Convert;
import com.mongodb.MongoClientSettings;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.weirdor.mongo.utils.ConfigFileUtils;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;

/**
 * mongoClient帮助类，用于从配置文件获取数据库连接
 * @Author werdor
 * @Date 2021/11/8 10:34 上午
 **/
@Slf4j
public class MongoClientHelper {

    private static Map<String, MongoClient> clientMap = new ConcurrentHashMap<>();

    private Logger logger = LoggerFactory.getLogger(MongoClientHelper.class);

    /**
     * 获取mongodb数据库连接
     *
     * @param configFilePath
     *            数据库连接的配置文件相对于classpath的路径
     * @return
     * @throws FileNotFoundException
     * @throws IOException
     */
    public MongoClient getClient(String configFilePath) throws FileNotFoundException, IOException {

        MongoClient client = clientMap.get(configFilePath);

        if (client != null) {
            logger.info("配置文件 {} 对应的客户端已存在，将被复用", configFilePath);
            clientMap.put(configFilePath, client);
            return client;
        }
        logger.info("配置文件 {} 对应的客户端不存在，将新建并缓存已被复用", configFilePath);

        Properties config = ConfigFileUtils.getConfigProperties(configFilePath);

        List<ServerAddress> seeds = new ArrayList<>();

        String[] userHosts = config.getProperty("host").split(",");
        for (String userHost : userHosts) {
            ServerAddress serverAddress = new ServerAddress(userHost, Convert.toInt(config.getProperty("port")));
            seeds.add(serverAddress);
        }
        String username = config.getProperty("username");
        String password = config.getProperty("password");

        if (username != null && !username.equals("") && password != null && !password.equals("")) {
            MongoCredential credential = MongoCredential.createScramSha1Credential(config.getProperty("username"),  config.getProperty("db"), config.getProperty("password").toCharArray());
            MongoClientSettings settings = MongoClientSettings.builder()
                    .applyToClusterSettings(builder ->
                            builder.hosts(seeds))
                    .credential(credential)
                    .build();
            client = MongoClients.create(settings);
            clientMap.put(configFilePath, client);
            return client;
        }

        // 未指定用户名密码
        client = MongoClients.create(
                MongoClientSettings.builder()
                        .applyToClusterSettings(builder ->
                                builder.hosts(seeds))
                        .build());
        return client;

    }

}
